package service

import (
	"fmt"
	"lib/structs/sys"
	"lib/structs/tables"
	"sys/dao"
)

var OrgService = new(orgService)

type orgService struct {
}

// GetSubList 获取下级部门
func (s orgService) GetSubList(parentId int64) (tree []sys.OrgNode, err error) {
	all, err := dao.OrgRepository.FindAll()
	if err != nil {
		return
	}
	tree = s.findNode(parentId, all)
	return
}

// findNode 递归获取下级部门树形结构
func (s orgService) findNode(parentId int64, li []tables.Org) (tree []sys.OrgNode) {
	for _, v := range li {
		if v.ParentId == parentId {
			node := sys.OrgNode{
				Id:       v.Id,
				OrgName:  v.OrgName,
				ParentId: v.ParentId,
				Mate:     v,
				Label:    v.OrgName,
				Value:    fmt.Sprintf("%d", v.Id),
				Children: []sys.OrgNode{},
			}
			subs := s.findNode(v.Id, li)
			node.Children = append(node.Children, subs...)
			tree = append(tree, node)
		}
	}
	return tree
}

// GetOrgMap 将部门封装成map结构
func (s orgService) GetOrgMap() (m map[int64]tables.Org) {
	m = make(map[int64]tables.Org)
	all, err := dao.OrgRepository.FindAll()
	if err != nil {
		return
	}
	for _, v := range all {
		m[v.Id] = v
	}
	return
}
